<?php
/**
 * (logic) 库存总表（fba库存）
 */

namespace App\Logic\Inventory;

use App\Models\Inventory\InventoryTotalArea;
use App\Models\SalesReport\FBAInventory;
use App\Models\Basics\SysICountry;
use Illuminate\Support\Facades\DB;

class SyncInventoryAreaFBAStock{

    /**
     * 运行时机：FBA库存报表,FBA收货报表有更新后
     * 设定：自定义运行
     */
    public static function exe(){

        try{
            $country = [];
            InventoryTotalArea::query()
                ->orderBy('id')
                ->chunkById(500, function ($items) use (&$country){

                    DB::beginTransaction();
                    foreach ($items as $_item){

                        if(!array_key_exists($_item->area_id, $country)){
                            $country[$_item->area_id] = SysICountry::getCountryIdsByAreaId($_item->area_id);
                        }

                        //FBA
                        $countryIds = $country[$_item->area_id];
                        $fbaInventory = FBAInventory::_getInventory($countryIds,$_item->psku_id);
                        if($fbaInventory){
                            $instant = $fbaInventory->quantity ?: 0;
                            $transit = $fbaInventory->inbound ?: 0;
                        }else{
                            $instant = 0;
                            $transit = 0;
                        }

                        //更新库存
                        $_item->fba_instant = $instant;
                        $_item->fba_transit = $transit;
                        $_item->save();
                    }
                    DB::commit();
                });
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

}
